<template>
  <el-dialog class="register" :visible.sync="dialogVisible" center width="600">
    <div slot="title" class="title">用户注册</div>
    <el-form
      ref="registerFormRef"
      :rules="registerRules"
      label-width="100px"
      :model="registerForm"
    >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          name="image"
          :action="avatarUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="registerForm.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="18">
            <el-input v-model="registerForm.code"></el-input>
          </el-col>
          <el-col :span="5">
            <img @click="changeCodeURL" class="code" :src="codeURL" alt="" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="18">
            <el-input v-model="registerForm.rcode"></el-input>
          </el-col>
          <el-col :span="5">
            <el-button @click="getRcode" class="code">获取验证码</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { sendSms, register } from '@/api/register'
import { Component, Vue, Watch } from 'vue-property-decorator'
@Component({})
export default class Register extends Vue {
  declare codeURL: string
  declare registerForm: any
  declare dialogVisible: boolean
  declare imageUrl: string

  data() {
    return {
      dialogVisible: false, // 显示&隐藏
      codeURL: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms', // 图形验证码地址
      imageUrl: '', // 显示头像地址
      avatarUrl: process.env.VUE_APP_BASEURL + '/uploads', // 上传头像地址
      registerForm: {
        avatar: '', // 头像地址
        username: '', // 昵称
        email: '', // 邮箱
        phone: '', // 手机号
        password: '', // 密码
        code: '', // 图形验证码
        rcode: '' // 验证码
      },
      registerRules: {
        avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          {
            validator: (rule: string, value: string, callback: Function) => {
              // eslint-disable-next-line
              const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

              if (!reg.test(value)) {
                callback(new Error('邮箱不合法'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            validator: (rule: string, value: string, callback: Function) => {
              // eslint-disable-next-line
              const reg = /^1[3456789][0-9]{9}$/

              if (!reg.test(value)) {
                callback(new Error('手机号不合法'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '密码长度在 6 到 12 个字符之间',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入图形验证码', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '验证码必须是4个字符',
            trigger: 'blur'
          }
        ],
        rcode: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          {
            min: 4,
            max: 4,
            message: '验证码必须是4个字符',
            trigger: 'change'
          }
        ]
      }
    }
  }
  @Watch('dialogVisible')
  dialogVisibleChange(newVal: boolean) {
    this.$nextTick(() => {
      ;(this.$refs.registerFormRef as any).clearValidate()
    })
  }
  // 更改图形验证码
  changeCodeURL() {
    this.codeURL =
      process.env.VUE_APP_BASEURL +
      '/' +
      '/captcha?type=sendsms&time=' +
      new Date()
  }
  // 上传成功
  beforeAvatarUpload(file: any) {
    const isJPG =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/gif'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
      this.$message.error('上传头像图片只能是 JPG 格式!')
    }
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
  }
  // 上传成功
  handleAvatarSuccess(res: any) {
    this.imageUrl = process.env.VUE_APP_BASEURL + '/' + res.data.file_path
    this.registerForm.avatar = res.data.file_path
  }
  // 获取验证码
  async getRcode() {
    const res = await sendSms('/sendsms', {
      code: this.registerForm.code,
      phone: this.registerForm.phone
    })

    if (res.data.code === 200) {
      this.registerForm.rcode = res.data.data.captcha
    } else {
      this.$message.error(res.data.message)
    }
  }
  // 提交
  async submit() {
    ;(this.$refs.registerFormRef as any).validate(async (valid: boolean) => {
      if (valid) {
        const res = await register('/register', this.registerForm)

        if (res.data.code === 200) {
          this.$message.success('注册成功~')

          this.dialogVisible = false
        } else {
          this.$message.error('注册失败~')
        }
      }
    })
  }
}
</script>

<style lang="scss">
.register {
  .title {
    height: 53px;
    background: #03c0f9;
    color: #fff;
    text-align: center;
    line-height: 53px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
  }
  .code {
    margin-left: 10px;
    width: 100%;
    height: 40px;
  }
  .avatar-uploader {
    width: 178px;
    margin: 0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
